package de.dopichaj.labrador.tools;


import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.SortedSet;

import de.dopichaj.labrador.index.Index;
import de.dopichaj.labrador.index.TagFactory;
import de.dopichaj.labrador.index.meta.DocumentDigest;
import de.dopichaj.labrador.index.meta.DocumentMetaData;
import de.dopichaj.labrador.search.hit.Hit;
import de.dopichaj.labrador.search.hit.HitHierarchyTree;
import de.dopichaj.labrador.search.merge.pattern.AbstractPattern;
import de.dopichaj.labrador.search.merge.pattern.PatternMerge;
import de.dopichaj.labrador.search.prune.ContextPruner;
import de.dopichaj.labrador.search.prune.ResultTreePruner;
import de.dopichaj.labrador.util.io.ByteReader;


public final class PatternFinder {

    final TagFactory tagFactory;

    final List<DocumentDigest> digests;

    public PatternFinder(Index index) throws IOException {
        final ByteReader reader = index.getDigestByteReader();

        // read the tag ID factory
        tagFactory = index.getTagFactory();

        // read the document digests
        digests = new ArrayList<DocumentDigest>();
        while (true) {

            System.err.print(".");
            System.err.flush();
            digests.add(new DocumentDigest(tagFactory, reader));
        }
    }

    public List<ContextInformation> getContextsMatching(String signaturePattern) {

        final SignatureMatchingPattern pattern =
            new SignatureMatchingPattern(signaturePattern);
        ResultTreePruner pruner = new ContextPruner(new PatternMerge(pattern));
        for (final DocumentMetaData digest : digests) {

            final HitHierarchyTree tree =
                new HitHierarchyTree(digest.getFragments().values());
            pruner.prune(tree);
        }
        System.err.println("finished searching for " + signaturePattern);
        return pattern.getMatchingContexts();
    }

    private static final class SignatureMatchingPattern extends AbstractPattern {

        private final String signaturePattern;

        private final List<ContextInformation> matchingContexts =
            new ArrayList<ContextInformation>();

        public SignatureMatchingPattern(String signaturePattern) {

            this.signaturePattern = signaturePattern;
        }

        @Override
        public void applyTo(Hit hit, SortedSet<Hit> children) {

            final StringBuilder signature = new StringBuilder(
                    String.valueOf(quantize(hit.getContentLength())));

            // for every child
            int lastPos = hit.getPosition();
            for (Hit child : children) {

                // if it does not immediately follow the last child, print a
                // text node
                assert child.getPosition() >= lastPos;
                if (child.getPosition() > lastPos) {
                    int diff = child.getPosition() - lastPos;
                    signature.append("t" + quantize(diff));
                    lastPos += diff;
                }

                // print the child
                signature.append("e"
                    + quantize(child.getContentLength()));
                lastPos += child.getContentLength();
            }

            if (lastPos < hit.getPosition() + hit.getContentLength()) {
                int diff = hit.getPosition() + hit.getContentLength() - lastPos;
                signature.append("t" + quantize(diff));
                lastPos += diff;
            }

            if (signature.toString().matches(signaturePattern)) {
                matchingContexts.add(new ContextInformation(
                    signature.toString(),
                    quantize(hit.getContentLength()),
                    hit.getFile(), hit.getXPath()));
            }
        }

        private int quantize(int n) {
            return n == 0 ? 0 : Math.min(9, (int)Math.floor(Math.log(n)
                / Math.log(10)));
        }

        public List<ContextInformation> getMatchingContexts() {
            return matchingContexts;
        }
    }
}
/*
Copyright (c) 2007 Philipp Dopichaj

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/